#include <iostream>
#include <fstream>
#include "contacts.pb.h"
using namespace std;
using namespace s_contacts;

void AddPeopleInfo(PeopleInfo* people){
    string name;
    int birthday;
    cout << "————————————————————新增联系人————————————————————" << endl;
    
    cout << "请输入联系人姓名: ";
    getline(cin, name);
    people->set_name(name);

    cout << "请输入联系人生日: ";
    cin >> birthday;
    cin.ignore(256, '\n'); // 清除输入缓冲区 -- 换行符
    people->set_birthday(birthday);


    for(int i = 0; i < 1; ++i){
        cout << "请输入联系人电话" << i + 1 << "(只输入回车完成电话新增): ";
        string number;
        getline(cin, number);
        if(number.empty()) break; // 如果输入为空，则结束电话输入
        else if(number.length() > 11){
            cout << "电话号码长度s不能超过11位, 请重新输入。" << endl;
            i--;
            continue;
        }
        PeopleInfo_Phone* phone = people->add_phone();
        phone->set_number(number);
    }

    cout << "————————————————————添加联系人成功————————————————————" << endl;
}


int main(){
    Contacts contacts;
    // 读取本地人已存在的联系人文件
    fstream input("../contacts.bin", ios::in | ios::binary);
    if(!input) cout << "contacts.bin not found, creating a new file." << endl;
    else if(!contacts.ParseFromIstream(&input)){    
        cout << "Failed to parse contacts.bin." << endl;
        input.close();
        return -1;
    }
    // 向通讯录添加一个联系人
    AddPeopleInfo(contacts.add_contacts());


   // 将联系人信息写入到文件中
    fstream output("../contacts.bin", ios::out | ios::trunc | ios::binary);
    if(!contacts.SerializeToOstream(&output)){
        cout << "Failed to write contacts.bin." << endl;
        input.close();
        output.close();
        return -1;
    }

    input.close();
    output.close();
    return 0;
}
